<?php
namespace Modules\File\Forms\Element;

use Phalcon\Di;
use Phalcon\Tag;
use Core\Forms\Element;
use Modules\File\Library\FileHandle;

class File extends Element
{
    public function getValue()
    {
        $file = [];
        $output = FileHandle::upload($this->_options, $this->_name);
        foreach ($output['success'] as $item) {
            if ($this->_name == $item['id']) {
                $file[] = $item['url'];
            }
        }

        if (count($file) == 1) {
            return end($file);
        }

        return $file;
    }

    public function render($attributes = null)
    {
        $initialPreview = [];
        $default = $this->_default;
        if(is_string($default)){
            $default = [$default];
        }elseif(is_array($default)){
            $default = array_values($default);
        }else{
            $default = [];
        }
        foreach ($default as $item){
            $initialPreview[] = "<img src='{$item}' />";
        }
        $initialPreview = json_encode($initialPreview);
        $script =
<<<scription
    $("#{$this->_name}").fileinput({
        language: 'zh',
        showPreview: true,
        showUpload: false,
        initialPreview: {$initialPreview}
    });
scription;

        $di = Di::getDefault();
        $di->getShared('assets')
            ->addJs('bootstrap-fileinput', '//cdn.bootcss.com/bootstrap-fileinput/4.3.8/js/fileinput.min.js', 'footer')
            ->addJs('bootstrap-fileinput-themes', '//cdn.bootcss.com/bootstrap-fileinput/4.3.8/themes/explorer/theme.min.js', 'footer')
            ->addJs('bootstrap-fileinput-local', '//cdn.bootcss.com/bootstrap-fileinput/4.3.8/js/locales/zh.js', 'footer')
            ->addCss('bootstrap-fileinput', '//cdn.bootcss.com/bootstrap-fileinput/4.3.8/css/fileinput.min.css', 'footer')
            ->addCss('bootstrap-fileinput', '//cdn.bootcss.com/bootstrap-fileinput/4.3.8/themes/explorer/theme.css', 'footer')
            ->addInlineJs('bootstrap-fileinput-' . $this->_name, $script, 'footer');

        return Tag::fileField($this->prepareAttributes($attributes));
    }
}
